<template>
  <el-form
    :model="userInfo"
    :rules="userInfoRules"
    ref="userForm"
    v-loading="loading"
  >
    <el-form-item label="个人头像" label-width="100px">
      <el-upload
        class="upload-item-info"
        :action="uploadAction"
        :headers="actionData"
        :before-upload="handleBeforeUpload"
        :on-change="handleChange"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        list-type="picture"
        :show-file-list="false"
        :auto-upload="true"
      >
        <el-button size="small" type="primary">选择图片</el-button>
      </el-upload>
      <td-image v-model="layerImg" @remove="removeImg"></td-image>
    </el-form-item>
    <el-form-item prop="realName" label="姓名" label-width="100px">
      <el-input
        v-model="userInfo.realName"
        placeholder="请输入您的姓名"
      ></el-input>
    </el-form-item>
    <el-form-item prop="telPhone" label="联系电话" label-width="100px">
      <el-input type="text" v-model="userInfo.telPhone"></el-input>
    </el-form-item>
    <el-form-item prop="email" label="个人邮箱" label-width="100px">
      <el-input type="text" v-model="userInfo.email"></el-input>
    </el-form-item>
    <el-form-item prop="address" label="详细地址" label-width="100px">
      <el-input type="text" v-model="userInfo.address"></el-input>
    </el-form-item>
    <el-form-item style="text-align: center;">
      <el-button type="danger" class="submit_btn" @click="onCloseUserDialog"
        >取消</el-button
      >
      <el-button
        type="primary"
        class="submit_btn"
        @click="onSubmitUserInfo('userForm')"
        >提交</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
import { userManage, uploadFile } from '@/api/index'
import TdImage from '@/components/TdImage.vue'
const userInfo = {
  // icon: '',
  realName: '',
  username: '',
  roleId: '',
  telPhone: '',
  email: '',
  address: ''
}
var baseUrl = process.env.VUE_APP_BASE_API

export default {
  name: '',
  componentName: '',
  components: { TdImage },
  data() {
    const validataTelPhone = (rule, value, callback) => {
      const phoneReg = /^1[3-9]\d{9}$/
      const telReg = /^([0\+]\d{2,3}-?)?(\d{7,8})?$/
      if (value) {
        if (phoneReg.test(value) || telReg.test(value)) {
          callback()
        } else {
          callback(new Error('您的电话号码输入有错误'))
        }
      } else {
        callback()
      }
    }
    const validatorEmail = (rule, value, callback) => {
      const emailReg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w)*/
      if (value) {
        if (!emailReg.test(value)) {
          callback(new Error('您的邮箱号输入有错误'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      loading: false,
      userInfo: userInfo,
      userInfoRules: {
        // 用户编辑 添加检验
        realName: [
          {
            type: 'string',
            required: true,
            message: '请输入您的姓名',
            trigger: 'blur'
          }
        ],
        telPhone: [{ validator: validataTelPhone, trigger: 'blur' }],
        email: [{ validator: validatorEmail, trigger: 'blur' }]
      },
      actionData: { Authorization: 'Bearer ' + localStorage.getItem('token') },
      uploadAction: baseUrl + '/batch/upload', // 头像upload
      uploadPicUrl: baseUrl, // 头像远端地址
      faceIds: null, // logo id
      fileList: [], // FormData list
      images: null, // 图片路径 无http
      layerImg: []
    }
  },
  props: {
    visible: Boolean
  },
  watch: {
    visible(newV, oldV) {
      if (newV) {
        this.getUserInfo()
      }
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    async getUserInfo() {
      this.loading = true
      try {
        const info = await userManage.getUserInfo()
        console.log(140, info.data)
        this.layerImg = []
        this.userInfo = info.data
        this.layerImg.push(this.uploadPicUrl + info.data.icon)
        this.loading = false
        this.$message.success('获取信息成功')
      } catch {
        this.loading = false
        this.$message.error('获取信息失败')
      }
    },
    // 文件操作 头像
    handleBeforeUpload(file) {
      let fileObj = {
        name: file.name,
        size: file.size,
        status: 'uploading...',
        process: 0,
        id: file.uid,
        type: /^image/.test(file.type)
      }
      if (!fileObj.type) {
        this.$message.error('这不是图片')
        return false
      }
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('上传文件过大', file.size)
        return false //必须返回false
      }
      this.fileList.push(file)
      this.uploadFileFace()
    },
    async uploadFileFace() {
      const files = new FormData()
      for (let i = 0; i < this.fileList.length; i++) {
        files.append('file', this.fileList[i])
      }
      try {
        const upload = await uploadFile.txUpload(files)
        console.log(upload)
        let layerImg = []
        this.images = upload.data.url
        this.faceIds = upload.data.id
        layerImg.push(this.uploadPicUrl + upload.data.url)
        this.layerImg = layerImg
        this.$message.success('图片上传成功')
      } catch {
        this.$message.error('错误')
      }
    },
    removeImg({ img, index }) {},
    handleChange() {},
    handlePreview() {},
    handleRemove() {},
    onCloseUserDialog() {
      this.$emit('submit', false)
    },
    onSubmitUserInfo(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.submitUserForm()
        } else {
          return false
        }
      })
    },
    async submitUserForm() {
      this.loading = true
      var userInfo = this.userInfo
      userInfo.icon = this.images
      try {
        const info = await userManage.editUser(userInfo)
        console.log(info)
        localStorage.setItem('icon', this.images)
        this.layerImg = []
        this.$emit('submit', true)
        this.loading = false
        this.$message.success({
          message: '修改成功了',
          duration: 2000
        })
      } catch {
        this.layerImg = []
        this.$emit('submit', false)
        this.loading = false
        this.$message.error({
          message: '噢，发现错误，联系后台管理员',
          duration: 2000
        })
      }
    }
  }
}
</script>
